<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @drag-sort="sortTable"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出用户数据</el-button>
        <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope.selectedListIds)">
          批量删除用户
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <template #avatar="{ row }">
        <el-image
          style="width: 80px; height: 80px"
          :preview-teleported="true"
          :src="row.avatar"
          :preview-src-list="[row.avatar]"
          fit="cover"
        />
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link>
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <UserDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import { User, WxUser } from "@/api/interface";
import { useHandleData, useWarnData } from "@/hooks/useHandleData";
import { useDownload, useDownloads } from "@/hooks/useDownload";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "@/views/system/components/UserDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh } from "@element-plus/icons-vue";
import { UserExport, deleteUserId, deleteListId, addUsers, update } from "@/api/modules/users";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/components/Loading/fullScreen";
import { getUserList, getUserExport, deleteIds, deleteId } from "@/api/modules/wxuser";

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

const dataCallback = (data: any) => {
  const baseUrl = import.meta.env.VITE_BACIL_IMG;
  const list = data.records.map((item: any) => {
    if (item.avatar && !item.avatar.startsWith("http")) {
      item.avatar = baseUrl + item.avatar;
    }
    return item;
  });
  return {
    list: list,
    total: data.total
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = async (params: any) => {
  showFullScreenLoading(); // 👈 开启 loading
  let newParams = JSON.parse(JSON.stringify(params));
  tryHideFullScreenLoading(); // 👈 关闭 loading
  console.log("newParams", newParams);
  return getUserList(newParams);
};
// 自定义渲染表头（使用tsx语法）
const headerRender = (scope: HeaderRenderScope<WxUser.ResWxUser>) => {
  return (
    <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
      {scope.column.label}
    </el-button>
  );
};

const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success(`已复制`);
  } catch (err) {
    ElMessage.error("复制失败");
  }
};
// 表格配置项
const columns = reactive<ColumnProps<WxUser.ResWxUser>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { type: "sort", label: "Sort", width: 80 },
  {
    prop: "username",
    label: "微信昵称",
    search: { el: "input", tooltip: "我是搜索提示" },
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => copyToClipboard(scope.row.username.toString())}>
          {scope.row.username}
        </el-button>
      );
    }
  },
  {
    prop: "avatar",
    label: "微信头像"
  },
  {
    prop: "phone",
    label: "联系电话",
    search: { el: "input" },
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => copyToClipboard(scope.row.phone.toString())}>
          {scope.row.phone}
        </el-button>
      );
    }
  },
  { prop: "email", label: "邮箱" },

  {
    prop: "createdTime",
    label: "创建时间"
  },
  { prop: "operation", label: "操作", fixed: "right", width: 180 }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};

// 删除用户信息
const deleteAccount = async (params: WxUser.ResWxUser) => {
  await useHandleData(deleteId, params.id, `删除【${params.username}】用户`);
  proTable.value?.getTableList();
};

// 批量删除用户信息
const batchDelete = async (id: string[]) => {
  await useHandleData(deleteIds, { id }, "删除所选用户信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 导出用户列表
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出用户数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownloads(getUserExport, "用户列表", proTable.value?.searchParam)
  );
};

// 批量添加用户
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<User.ResUserList> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title == "新增" ? addUsers : title === "编辑" ? update : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
